Variables are created by:
- int a=5; (we have some area in memory with value 5 and we refer it with name 'a')
- We need to ask where is this variable located in memory, we have an operator(&a) called 'address of' which stores the address of varialbe 'a'.
- address are stored with 12 characters of hexadecimal numbers. ex. 0xAEC034523823 . storing this number requires 12.4=48 bits of memory. (becuase each hexadecimal number is from 0 to 15(F), and 4 bits are sufficient to store any hexadecimal number)
- since 4 bytes (32 bits) are sufficient for storing address we can use integer data type to store address of variable.
- pointers points/stores address of varialbe so they are declared and assigned by : int * p=&a; (here p is pointer varialbe which will store address of varialbe 'a')
Reference is an alias or another name for any given variable.
The way we create an alias is:
#include<iostream> int main() { int a=5; int & b=a; //here b is an alias of a, now we can access the variable a by two methods, a or b. std::cout<<a<<'\t'<<b; //(int &b, int & b , int& b - all are same) }
Behind the scenes references uses pointers, but we don't need to go to that level.
- References are majorly used when we are passing large amount of data in a function, when we pass data inside a function we generally copy that data to parameter variables. Have a look below the use of references:
#include<iostream> int add(int &a, int &b) { int c=a+b; return c; } int main() { int x=50; int y=40; std::cout<<add(x,y); // in this way the data 50 and 40 is not copied in any variable, and it saves memory, it is useful when passing billions of data points in a function or passing a vector. It helps in saving memory. return 0; }
-
Like pointers any changes made to alias does not remains inside the function only, and changes will reflect outside the function as well.
code:
#include<iostream> void increment(int &a) { a++; } int main() { int x=5; increment(x); std::cout<<x; //it will print 6 return 0; }
-
Location we set to alias/reference is permanent, once we set an alias, we can not make it alias to something else.
int a=3; int c=30; int &b=a; b=c; // this statement will store value of c in b which points to address of a, so a=30=b=c return 0;
-
Alias and original variable has same address and it can be checked by following code:
#include<iostream> int main() { int a=5; int &b=a; std::cout<<&a<<'\t'<<&b; return 0; }